package com.sunwayworld.basemodule.business.pjtask.computing;

import com.sunwayworld.basemodule.basedata.specjudgetype.bean.LimsSpecJudgeTypeBean;
import com.sunwayworld.basemodule.basedata.specjudgetype.service.LimsSpecJudgeTypeService;
import com.sunwayworld.basemodule.business.pjtask.bean.LimsPjTaskBean;
import com.sunwayworld.basemodule.business.pjtask.computing.formula.PjTaskFormulaRepository;
import com.sunwayworld.basemodule.business.pjtask.service.LimsPjTaskService;
import com.sunwayworld.basemodule.common.utils.ConditionUtils;
import com.sunwayworld.basemodule.common.utils.GikamFormulaHelperUtils;
import com.sunwayworld.basemodule.coredata.pjproduct.bean.CurrentConditionDTO;
import com.sunwayworld.basemodule.coredata.pjproduct.bean.LimsProductConditionBean;
import com.sunwayworld.basemodule.coredata.pjproduct.bean.LimsPurposeMethodReferBean;
import com.sunwayworld.basemodule.coredata.pjproduct.service.LimsProductConditionService;
import com.sunwayworld.basemodule.coredata.pjproduct.service.LimsPurposeMethodReferService;
import com.sunwayworld.basemodule.coredata.test.bean.LimsPossibleResultBean;
import com.sunwayworld.basemodule.coredata.test.service.LimsPossibleResultService;
import com.sunwayworld.basemodule.samplemanage.sample.bean.LimsSampleBean;
import com.sunwayworld.basemodule.samplemanage.sample.service.LimsSampleService;
import com.sunwayworld.framework.beans.BeanPropertyEvent;
import com.sunwayworld.framework.beans.BeanPropertyListener;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.exception.RoundingRuleException;
import com.sunwayworld.framework.formula.GikamComputingDataHolder;
import com.sunwayworld.framework.formula.GikamComputingEngine;
import com.sunwayworld.framework.i18n.I18nHelper;
import com.sunwayworld.framework.mybatis.mapper.MapperParameter;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.script.BshExecutor;
import com.sunwayworld.framework.utils.*;
import com.sunwayworld.module.sys.rounding.bean.CoreRoundingRuleBean;
import com.sunwayworld.module.sys.rounding.service.CoreRoundingRuleService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 普检公式计算、结果判定
 *
 * @author maj@sunwayworld.com
 * @date 2022-03-15
 */
public class PjTaskComputingEngine implements GikamComputingEngine {
    // 任务单下的结果集
    public static final String FOLDER_ORDER_TASK_PJ_LIST = "FOLDER_ORDER_TASK_PJ_LIST";
    // 任务单下的样本
    public static final String FOLDER_SAMPLE_LIST = "FOLDER_SAMPLE_LIST";
    // 检测项目备选结果集
    public static final String POSSIBLE_RESULT_LIST = "POSSIBLE_RESULT_LIST";
    // 任务单下的条件配置
    public static final String FOLDER_PRODUCT_CONDITION_LIST = "FOLDER_PRODUCT_CONDITION_LIST";
    // 当前任务下的条件值如性别值
    public static final String ORDER_CURRENT_CONDITION_LIST = "ORDER_CURRENT_CONDITION_LIST";
    // 任务单下的参考值
    public static final String FOLDER_PRODUCT_REFER_LIST = "FOLDER_PRODUCT_REFER_LIST";
    //判定结果类型
    public static final String SPEC_JUDGE_TYPE_PJ_LIST = "SPEC_JUDGE_TYPE_PJ_LIST";

    //特殊符号
    public static final String LOGIC_CALCULATE_CHAR = "\\d*[<|>|>=|<=|≤|≥]\\d*";

    private static final Logger logger = LogManager.getLogger(PjTaskComputingEngine.class);

    private List<Long> folderEquipIdList;

    private PjTaskComputingEngine() {
    }

    public static PjTaskComputingEngine getEngine(List<Long> folderIdList) {
        PjTaskComputingEngine engine = new PjTaskComputingEngine();
        engine.folderEquipIdList = folderIdList;
        return engine;
    }

    public static void main(String[] args) {
        Class<PjTaskFormulaRepository> pjTaskFormulaRepositoryClass = PjTaskFormulaRepository.class;
        System.out.println(pjTaskFormulaRepositoryClass.getName());
    }

    @Override
    public BshExecutor getBshExecutor() {
        BshExecutor bsh = BshExecutor.instance();

        bsh.eval("import com.sunwayworld.framework.utils.StringUtils;");
        bsh.eval("import com.sunwayworld.framework.utils.ArithUtils;");
        bsh.eval("import com.sunwayworld.basemodule.business.pjtask.computing.formula.PjTaskFormulaRepository.*;");


        bsh.eval("import java.text.*;");

//        GikamFormulaRegistry.INSTANCE.getRepository().forEach(c -> {
//            bsh.eval("import static " + c.getName() + ".*;");
//        });

        return bsh;
    }

    @Override
    public void processData() {
        LimsPjTaskService taskResultService = ApplicationContextHelper.getBean(LimsPjTaskService.class);
        List<LimsPjTaskBean> updateTaskResultList = new ArrayList<>();
        // 获取更新的字段
        Set<String> updatedColumnList = new HashSet<>();
        List<LimsPjTaskBean> orderTaskList = GikamComputingDataHolder.get(FOLDER_ORDER_TASK_PJ_LIST);

        for (LimsPjTaskBean taskResult : orderTaskList) {
            BeanPropertyListener proxy = (BeanPropertyListener) taskResult;

            List<BeanPropertyEvent> propertyEventList = proxy.getChangedPropertyEventList().stream().filter(p -> !ObjectUtils.equals(p.getOldValue(), p.getNewValue())).collect(Collectors.toList());

            if (!propertyEventList.isEmpty()) {
                updateTaskResultList.add(taskResult);
                propertyEventList.forEach(p -> updatedColumnList.add(p.getPropertyDescriptor().getName().toUpperCase()));
            }
        }

        if (!updateTaskResultList.isEmpty() && !updatedColumnList.isEmpty()) {
            taskResultService.getDao().fastUpdate(updateTaskResultList, updatedColumnList.toArray(new String[0]));
        }
    }

    @Override
    public void run(BshExecutor bsh) {
        boolean dependencyCheck = this.isDependencyCheck();
        List<LimsPjTaskBean> folderOrderTaskBeans = GikamComputingDataHolder.get(FOLDER_ORDER_TASK_PJ_LIST);
        for (LimsPjTaskBean pjTaskBean : folderOrderTaskBeans) {
            GikamComputingDataHolder.setCurrentData(pjTaskBean);
            String script = GikamFormulaHelperUtils.getRevisedScript(pjTaskBean.getFormula());
            try {
                String originResult = pjTaskBean.getOriginResult(); // 录入的原始结果

                if (!StringUtils.isEmpty(script)) {
                    Object resultValue = bsh.eval(script);
                    if (!ObjectUtils.isEmpty(resultValue)) {
                        String finalResultValue = resultValue.toString();
                        if (!dependencyCheck && !StringUtils.isEmpty(finalResultValue)) {
                            pjTaskBean.setFinalResult(finalResultValue);
                            originResult = finalResultValue;
                        }
                    }
                }

                if (!dependencyCheck && !StringUtils.isEmpty(originResult)) {
                    String finalResult = originResult;
                    String roundingRule = pjTaskBean.getRoundingRule();
                    if (!StringUtils.isEmpty(roundingRule) && NumberUtils.isNumber(finalResult) && !StringUtils.equals(roundingRule, "NONE")) {
                        finalResult = this.rounding(finalResult, roundingRule);
                    }
                    pjTaskBean.setFinalResult(finalResult);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                GikamComputingDataHolder.removeCurrentData();
            }
            if (!dependencyCheck) {
                setJudge(pjTaskBean);
            }
        }

    }

    @Override
    public void sortData() {

    }

    /**
     * 初始化所需数据
     */
    @Override
    public void initData() {
        // 普检 一个folder对应一个orderTask
        LimsPjTaskService orderTaskService = ApplicationContextHelper.getBean(LimsPjTaskService.class);
        LimsPossibleResultService possibleResultService = ApplicationContextHelper.getBean(LimsPossibleResultService.class);
        LimsProductConditionService productConditionService = ApplicationContextHelper.getBean(LimsProductConditionService.class);
        LimsPurposeMethodReferService productReferService = ApplicationContextHelper.getBean(LimsPurposeMethodReferService.class);
        LimsSampleService sampleService = ApplicationContextHelper.getBean(LimsSampleService.class);
        MapperParameter temp = new MapperParameter();
        //根据folderIdList查询项目结果
        temp.setFilter(SearchFilter.instance().match("folderEquipId", folderEquipIdList).filter(MatchPattern.OR));
        List<LimsPjTaskBean> folderOrderTaskBeans = orderTaskService.selectList(temp);
        if (!folderOrderTaskBeans.isEmpty()) {
            List<Long> sampleIdList = folderOrderTaskBeans.stream().map(e -> e.getExt$Item("sampleId")).filter(Objects::nonNull)
                    .distinct().map(Long::parseLong).collect(Collectors.toList());
            List<LimsSampleBean> sampleBeanList = sampleService.selectForFormula(sampleIdList);
            GikamComputingDataHolder.put(FOLDER_SAMPLE_LIST, sampleBeanList);

            // 获取FOLDER下代理类
            List<LimsPjTaskBean> taskResultProxyList = ObjectUtils.clone(folderOrderTaskBeans).stream().map(BeanUtils::getPropertyListenerProxy).collect(Collectors.toList());
            GikamComputingDataHolder.put(FOLDER_ORDER_TASK_PJ_LIST, taskResultProxyList);
            //获取备选结果，如果值等同于备选结果的其中一个，就同步其判定结果，优先级低于分析项的判定依据
            List<Long> purposeIds = folderOrderTaskBeans.stream().map(LimsPjTaskBean::getPurposeId)
                    .distinct().collect(Collectors.toList());
            temp.clear();
            temp.setFilter(SearchFilter.instance().match("analyteId", purposeIds).filter(MatchPattern.OR));
            List<LimsPossibleResultBean> possibleResultList = possibleResultService.selectList(temp);
            GikamComputingDataHolder.put(POSSIBLE_RESULT_LIST, CollectionUtils.isEmpty(possibleResultList) ? CollectionUtils.emptyList() : possibleResultList);
            //根据项目获取判定条件
            List<Long> purposeMethodIds = folderOrderTaskBeans.stream().map(LimsPjTaskBean::getPurposeMethodId)
                    .distinct().collect(Collectors.toList());
            temp.clear();
            temp.setFilter(SearchFilter.instance().match("productMethodId", purposeMethodIds).filter(MatchPattern.OR));
            List<LimsProductConditionBean> productConditionBeans = productConditionService.selectList(temp);
            GikamComputingDataHolder.put(FOLDER_PRODUCT_CONDITION_LIST, productConditionBeans);
            //查询所有的参考范围
            temp.clear();
            temp.setFilter(SearchFilter.instance().match("purposemethodid", purposeMethodIds).filter(MatchPattern.OR));
            List<LimsPurposeMethodReferBean> productReferBeans = productReferService.selectList(temp);
            GikamComputingDataHolder.put(FOLDER_PRODUCT_REFER_LIST, CollectionUtils.isEmpty(productReferBeans) ? CollectionUtils.emptyList() : productReferBeans);

            if (!productConditionBeans.isEmpty()) {
                temp.clear();
                String tableFields = generalTableField(productConditionBeans);
                temp.put("folderEquipIds", StringUtils.join(folderEquipIdList, ","));
                temp.put("tableFields", tableFields);
                List<CurrentConditionDTO> currentConditionList = orderTaskService.selectCurrentConditionByTask(temp);
                GikamComputingDataHolder.put(ORDER_CURRENT_CONDITION_LIST, CollectionUtils.isEmpty(currentConditionList) ? CollectionUtils.emptyList() : currentConditionList);
            } else {
                GikamComputingDataHolder.put(ORDER_CURRENT_CONDITION_LIST, CollectionUtils.emptyList());
            }

            //不合格判定结果类型
            LimsSpecJudgeTypeService specJudgeTypeService = ApplicationContextHelper.getBean(LimsSpecJudgeTypeService.class);
            List<LimsSpecJudgeTypeBean> specJudgeTypeBeans = specJudgeTypeService.selectListByFilter(SearchFilter.instance()
                    .match("activedFlag", "1").filter(MatchPattern.EQ));
            GikamComputingDataHolder.put(SPEC_JUDGE_TYPE_PJ_LIST, specJudgeTypeBeans);
        }
    }

    private void setJudge(LimsPjTaskBean pjTaskBean) {
        List<LimsPossibleResultBean> possibleResultList = GikamComputingDataHolder.get(POSSIBLE_RESULT_LIST);
        possibleResultList.forEach(possibleResult -> {
            if (ObjectUtils.equals(possibleResult.getAnalyteId(), pjTaskBean.getPurposeId()) && StringUtils.equals(possibleResult.getOriginalResult(), pjTaskBean.getFinalResult())) {
                pjTaskBean.setJudge(possibleResult.getJudge());
            }
        });
        // 有结果才判定
        boolean orderTaskFlag = StringUtils.isEmpty(pjTaskBean.getFinalResult());

        //有默认值

        List<LimsSpecJudgeTypeBean> specJudgeTypeBeans = GikamComputingDataHolder.get(SPEC_JUDGE_TYPE_PJ_LIST);
        Map<String, LimsSpecJudgeTypeBean> map = new HashMap<>();
        if (!CollectionUtils.isEmpty(specJudgeTypeBeans)) {
            map = specJudgeTypeBeans.stream().collect(Collectors.toMap(LimsSpecJudgeTypeBean::getId, t -> t));
        }
        List<LimsPurposeMethodReferBean> productReferBeanList = GikamComputingDataHolder.get(FOLDER_PRODUCT_REFER_LIST);
        List<LimsProductConditionBean> conditionDTOList = GikamComputingDataHolder.get(FOLDER_PRODUCT_CONDITION_LIST);
        List<CurrentConditionDTO> currentConditionList = GikamComputingDataHolder.get(ORDER_CURRENT_CONDITION_LIST);
        // 筛选出当前任务下的参考范围、条件和条件值
        List<CurrentConditionDTO> currentConditionDTOS = currentConditionList.stream().filter(e -> e.getId().equals(pjTaskBean.getId())).collect(Collectors.toList());
        List<LimsPurposeMethodReferBean> productReferBeans = productReferBeanList.stream().filter(e -> e.getPurposeMethodId().equals(pjTaskBean.getPurposeMethodId())).collect(Collectors.toList());
        productReferBeans.forEach(referBean -> {
            List<LimsProductConditionBean> conditionDTOS = conditionDTOList.stream().filter(e -> e.getProductReferId().equals(referBean.getId())).collect(Collectors.toList());
            if (!conditionDTOS.isEmpty()) {
                referBean.setSorter(0);
                referBean.setConditionBeanList(conditionDTOS);
            } else {
                referBean.setSorter(1);
            }
        });
        // 清空参考值和范围，重新设置
        pjTaskBean.setReferRange(null);
        // 将有条件的排在前面
        productReferBeans.sort(Comparator.comparingInt(LimsPurposeMethodReferBean::getSorter));
        for (LimsPurposeMethodReferBean referBean : productReferBeans) {
            String[] referRange = new String[3];
            // 获取对应批次条件
            List<LimsProductConditionBean> conditionDTOS = referBean.getConditionBeanList();
            if (referBean.getReferType().equalsIgnoreCase("range")) {
                //定量方式处理
                ConditionUtils.getEvalValue(referBean.getReferLow(), referBean.getReferHigh(), referRange);
            } else if (referBean.getReferType().equalsIgnoreCase("fixed")) {
                //定性方法处理
                ConditionUtils.getEvalValue(referBean.getReferValue(), referRange);
            }

            if (!CollectionUtils.isEmpty(conditionDTOS)) {
                Map<String, List<LimsProductConditionBean>> listMap = conditionDTOS.stream().collect(Collectors.groupingBy(LimsProductConditionBean::getLotCode));
                if (toCompareCondition(currentConditionDTOS, listMap)) {
                    this.setReferRange(pjTaskBean, referRange[0], referBean.getExt$Item("judgename"));
                }
            } else {
                this.setReferRange(pjTaskBean, referRange[0], referBean.getExt$Item("judgename"));
            }
        }
        if (!orderTaskFlag) {
            for (LimsPurposeMethodReferBean referBean : productReferBeans) {
                //判定 经常出现数值 Double.parseDouble 错误，仪器传过来的值非一定是数值， 直接吃掉
                try {
                    // 先校验参考范围是否满足
                    Set<Boolean> flag = new HashSet<>();
                    flag.add(true);
                    String[] referRange = new String[3];
                    List<Integer> highOrLow = new ArrayList<>();
                    // 获取对应批次条件
                    List<LimsProductConditionBean> conditionDTOS = referBean.getConditionBeanList();
                    if (referBean.getReferType().equalsIgnoreCase("range")) {
                        if (NumberUtils.isNumber(pjTaskBean.getFinalResult())) {
                            //定量方式处理
                            ConditionUtils.getEvalValue(referBean.getReferLow(), referBean.getReferHigh(), Double.parseDouble(pjTaskBean.getFinalResult()), flag, highOrLow, referRange);
                        } else {
                            flag.add(false);
                        }
                    } else if (referBean.getReferType().equalsIgnoreCase("fixed")) {
                        //定性方法处理
                        ConditionUtils.getEvalValue(referBean.getReferValue(), pjTaskBean.getFinalResult(), flag, referRange);
                    }
                    // 满足
                    if (IsFalseOrTrue(flag)) {
                        boolean update = true;// 有条件，先判断条件满足 更新判断结果
                        if (!CollectionUtils.isEmpty(conditionDTOS)) {
                            Map<String, List<LimsProductConditionBean>> listMap = conditionDTOS.stream().collect(Collectors.groupingBy(LimsProductConditionBean::getLotCode));
                            update = toCompareCondition(currentConditionDTOS, listMap);
                        }
                        if (update) {
                            String tip = referBean.getDangerTip();
                            if (map.containsKey(tip)) {
                                LimsSpecJudgeTypeBean judgeTypeBean = map.get(tip);
                                pjTaskBean.setJudge(judgeTypeBean.getJudgeName());
                                pjTaskBean.setColor(judgeTypeBean.getColor());
                                if ("1".equalsIgnoreCase(judgeTypeBean.getPendingFlag())) {
                                    pjTaskBean.setResultStatus("abnormal");// 异常
                                    if (StringUtils.equals(referBean.getDatatype(), "1")) {
                                        pjTaskBean.setResultStatus("danger");// 危急
                                    }
                                }
                            }
                        }
                        break;
                    } else {
                        String tip = referBean.getDangerTip();
                        if (map.containsKey(tip)) {
                            LimsSpecJudgeTypeBean judgeTypeBean = map.get(tip);
                            // 不满足条件，则插入不满足条件的逻辑
                            if (referBean.getReferType().equalsIgnoreCase("range")) {
                                if (NumberUtils.isNumber(pjTaskBean.getFinalResult())) {
                                    //定量方式处理
                                    if (judgeTypeBean.getJudgeName().equals("-")) {
                                        // 如果范围标注是- ，则低于下限标注↓，否则标注↑
                                        if (!highOrLow.isEmpty()) {
                                            if (highOrLow.get(0).equals(1)) {
                                                specJudgeTypeBeans.stream().filter(sc -> sc.getJudgeName().equals("↓")).findFirst().ifPresent(sc -> {
                                                    pjTaskBean.setJudge(sc.getJudgeName());
                                                    pjTaskBean.setColor(sc.getColor());
                                                    if ("1".equalsIgnoreCase(sc.getPendingFlag())) {
                                                        pjTaskBean.setResultStatus("abnormal");// 异常
                                                        if (StringUtils.equals(referBean.getDatatype(), "1")) {
                                                            pjTaskBean.setResultStatus("danger");// 危急
                                                        }
                                                    }
                                                });
                                            } else if (highOrLow.get(0).equals(2)) {
                                                specJudgeTypeBeans.stream().filter(sc -> sc.getJudgeName().equals("↑")).findFirst().ifPresent(sc -> {
                                                    pjTaskBean.setJudge(sc.getJudgeName());
                                                    pjTaskBean.setColor(sc.getColor());
                                                    if ("1".equalsIgnoreCase(sc.getPendingFlag())) {
                                                        pjTaskBean.setResultStatus("abnormal");// 异常
                                                        if (StringUtils.equals(referBean.getDatatype(), "1")) {
                                                            pjTaskBean.setResultStatus("danger");// 危急
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    }
                                }
                                if (judgeTypeBean.getJudgeName().equals("合格")) {
                                    specJudgeTypeBeans.stream().filter(sc -> sc.getJudgeName().equals("不合格")).findFirst().ifPresent(sc -> {
                                        pjTaskBean.setJudge(sc.getJudgeName());
                                        pjTaskBean.setColor(sc.getColor());
                                        if ("1".equalsIgnoreCase(sc.getPendingFlag())) {
                                            pjTaskBean.setResultStatus("abnormal");// 异常
                                            if (StringUtils.equals(referBean.getDatatype(), "1")) {
                                                pjTaskBean.setResultStatus("danger");// 危急
                                            }
                                        }
                                    });
                                }
                            } else if (referBean.getReferType().equalsIgnoreCase("fixed")) {
                                //定性方法处理
                                if (judgeTypeBean.getJudgeName().equals("合格")) {
                                    specJudgeTypeBeans.stream().filter(sc -> sc.getJudgeName().equals("不合格")).findFirst().ifPresent(sc -> {
                                        pjTaskBean.setJudge(sc.getJudgeName());
                                        pjTaskBean.setColor(sc.getColor());
                                        if ("1".equalsIgnoreCase(sc.getPendingFlag())) {
                                            pjTaskBean.setResultStatus("abnormal");// 异常
                                            if (StringUtils.equals(referBean.getDatatype(), "1")) {
                                                pjTaskBean.setResultStatus("danger");// 危急
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    private void setReferRange(LimsPjTaskBean pjTaskBean, String referRange, String judgeName) {
        String unit = StringUtils.isEmpty(pjTaskBean.getUnit()) ? "" : pjTaskBean.getUnit();
        judgeName = StringUtils.isEmpty(judgeName) ? "" : judgeName;
        if (StringUtils.isEmpty(pjTaskBean.getReferRange())) {
            pjTaskBean.setReferRange(referRange);
            pjTaskBean.setScope(judgeName + "  " + referRange + "  " + unit);
        } else {
            String referValue = pjTaskBean.getReferRange();
            List<String> rsList = ArrayUtils.asList(referValue.split(",")).stream().collect(Collectors.toList());
            if (!rsList.contains(referRange)) {
                pjTaskBean.setReferRange(referValue + "," + referRange);
                pjTaskBean.setScope(pjTaskBean.getScope() + "\r\n" + judgeName + "  " + referRange + "  " + unit);
            }
        }
    }

    private Boolean toCompareCondition(List<CurrentConditionDTO> currentConditionDTOS, Map<String, List<LimsProductConditionBean>> listMap) {
        CurrentConditionDTO currentCondition = currentConditionDTOS.get(0);
        boolean bool = true;
        // 参考范围下所有条件批次下的条件都满足
        for (String lotCode : listMap.keySet()) {
            Set<Boolean> flag = new HashSet<>();
            flag.add(true);
            List<LimsProductConditionBean> conditionList = listMap.get(lotCode);
            if (!conditionList.isEmpty()) {
                for (LimsProductConditionBean condition : conditionList) {
                    if (!ObjectUtils.isEmpty(currentCondition.getExt$Item(condition.getColumnName()))) {
                        String currentValue = currentCondition.getExt$Item(condition.getColumnName());
                        if (condition.getColumnName().equalsIgnoreCase("age")) {
                            Double currentAge = ConditionUtils.getAgeValue(currentCondition.getCollectTime(), currentCondition.getBirthday());
                            if (condition.getConditionType().equalsIgnoreCase("range")) {
                                //定量处理
                                ConditionUtils.getEvalValue(condition.getColumnLow(), condition.getColumnHigh(), currentAge, flag);
                            } else if (condition.getConditionType().equalsIgnoreCase("fixed")) {
                                //定性处理
                                ConditionUtils.getEvalValue(condition.getColumnValue(), String.valueOf(currentAge), flag);
                            }
                        } else if (condition.getColumnName().equalsIgnoreCase("gender")) {
                            if (condition.getConditionType().equalsIgnoreCase("fixed")) {
                                //定性处理
                                ConditionUtils.getEvalValue(condition.getColumnValue(), currentValue, flag);
                            } else if (condition.getConditionType().equalsIgnoreCase("range")) {
                                //定量处理
                                ConditionUtils.getEvalValue(condition.getColumnValue(), currentValue, flag);
                            }
                        } else {
                            if (condition.getConditionType().equalsIgnoreCase("fixed")) {
                                //定性处理
                                ConditionUtils.getEvalValue(condition.getColumnValue(), currentValue, flag);
                            } else if (condition.getConditionType().equalsIgnoreCase("range")) {
                                //定量处理
                                ConditionUtils.getEvalValue(condition.getColumnLow(), condition.getColumnHigh(), Double.parseDouble(currentValue), flag);
                            }
                        }
                    } else {
                        bool = false;
                        return bool;
                    }
                    bool = IsFalseOrTrue(flag);
                    if (!bool) return bool;
                }
            }
        }
        return bool;
    }

    private boolean IsFalseOrTrue(Set<Boolean> flag) {
        List<Boolean> boolList = new ArrayList<>(flag);
        Boolean bool;
        if (boolList.size() == 2) {
            bool = false;
        } else {
            bool = boolList.get(0);
        }
        return bool;
    }

    private String generalTableField(List<LimsProductConditionBean> productConditionBeans) {
        Map<String, Object> hashMap = productConditionBeans.stream().collect(HashMap::new, (m, v) -> m.put(v.getDataSource().toLowerCase() + "." + v.getColumnName().toUpperCase(), v.getColumnName().toUpperCase()), HashMap::putAll);
        return StringUtils.join(hashMap.keySet(), ",");
    }

    public static String rounding(String data, String roundingScheme) {
        if (StringUtils.isEmpty(data)) {
            return null;
        }
        String roundingRuleId = StringUtils.split(roundingScheme, ",")[0];
        CoreRoundingRuleBean roundingRule = (CoreRoundingRuleBean) ((CoreRoundingRuleService) ApplicationContextHelper.getBean(CoreRoundingRuleService.class)).selectByIdIfPresent(roundingRuleId);
        if (!NumberUtils.isNumber(data)) {
            if (roundingScheme.contains("LKD")) {
                BshExecutor bsh = BshExecutor.instance();
                bsh.eval("import com.sunwayworld.framework.utils.StringUtils;");
                bsh.eval("import com.sunwayworld.framework.utils.NumberUtils;");
                bsh.eval("import java.math.BigDecimal;");
                bsh.eval("import java.math.RoundingMode;");
                bsh.eval("import java.util.regex.Pattern;");
                bsh.eval("import java.lang.String;");
                bsh.set("data", data);
                String result = (String) bsh.eval(roundingRule.getScript());
                return result;
            } else {
                throw new InvalidDataException("GIKAM.EXCEPTION.ROUNDING_NAN");
            }
        } else if (!StringUtils.isEmpty(roundingScheme) && !"NONE".equals(roundingScheme) && !"无修约规则".equals(roundingScheme)) {

            if (roundingRule != null && !"1".equals(roundingRule.getLastSuspendedFlag())) {
                if (ObjectUtils.isEmpty(roundingRule.getScript())) {
                    throw new RoundingRuleException(roundingRule.getRuleName() + I18nHelper.getMessage("GIKAM.EXCEPTION.ROUNDINGRULE_SCRIPT_NOT_EXISTS", new String[0]));
                } else {
                    int numberCnt = NumberUtils.parseInt(StringUtils.split(roundingScheme, ",")[1]);
                    BshExecutor bsh = BshExecutor.instance();
                    bsh.eval("import com.sunwayworld.framework.utils.StringUtils;");
                    bsh.eval("import com.sunwayworld.framework.utils.NumberUtils;");
                    bsh.eval("import java.math.BigDecimal;");
                    bsh.eval("import java.math.RoundingMode;");
                    bsh.eval("import java.util.regex.Pattern;");
                    bsh.set("data", data);
                    bsh.set("numberCnt", numberCnt);
                    String result = (String) bsh.eval(roundingRule.getScript());
                    return result;
                }
            } else {
                throw new RoundingRuleException("GIKAM.EXCEPTION.ROUNDINGRULE_EXISTS");
            }
        } else {
            return data;
        }
    }
}
